<template>
	<view v-if="orderData" class="my-page-color">
		<view class="padding36 bg-white mb15">
		
			<view @click="viewRefund"
				v-if="[4,5,7,8].includes(orderData.internal_status) "
				class="my-title">
				<span v-if="orderData.status == 4 && orderData.internal_status == 5">
					 订单已取消
				</span>
				<span v-else-if="orderData.status == 4">
					 取消订单待退款
				</span>
				
				<span v-else> {{statusList[orderData.internal_status]}}</span>
				<van-icon name="arrow" />
			</view>
		
			<view v-else class="my-title">
				{{statusList[orderData.internal_status]}}
			</view>
			

			<view class="color-orange mb40">
				<span v-if="orderData.internal_status == 0">提交成功，等待ViHome管家确认</span>
				<span class="center-vertical" v-else-if="orderData.internal_status == 1">
					管家已确认，支付剩余时间 <van-count-down color="color-orange" :time="countDownTime" />
				</span>
				
				<span v-else-if="orderData.internal_status == 2">支付成功</span>
				<span
					v-else-if="orderData.status == 3 &&orderData.cancel_operator_type != 3 && orderData.internal_status != 5">{{orderData.cancel_operator_type==1?'房客':'房东'}}取消订单，原因：
					{{orderData.cancel_reason}} </span>
				<span
					v-else-if="orderData.status == 3 &&orderData.cancel_operator_type == 3 && orderData.internal_status != 5">{{orderData.cancel_reason}}
				</span>
				
		
				<span
					v-else-if="orderData.internal_status == 10 ">押金{{orderData.deposit}}加元，将于10个工作日内退回至原支付账户</span>
				</span>
				<span
					v-else-if="[4,7,8].includes(orderData.internal_status) &&orderData.status == 4 ">退款金额{{orderData.refund_order.refund_amount}}加元，将于10个工作日内退回至原支付账户</span>
				</span>
				
				<span
					v-else-if="[4,7,8].includes(orderData.internal_status) ">退款金额{{orderData.refund_order.refund_amount}}加元，将于10个工作日内退回至原支付账户</span>
				<span
					v-else-if="orderData.internal_status == 5 ">退款金额{{orderData.refund_order.refund_amount}}加元，已退回至原支付账户</span>
				<span v-else-if="orderData.internal_status == 6">押金{{orderData.refund_order.refund_deposit}}加元，已退回至原支付账户</span>

			</view>
			
			
			
			<view v-if="orderData.internal_status == 0" class="center-all">
				<view v-if="orderData.cancelFlag" @click="cancelOrder" class="my-disable-btn ">取消订单</view>
				<view v-if="userInfo.role == 1" @click="showerweima" class="ml20  my-yellow-btn ">联系ViHome管家</view>
				<view v-if="userInfo.role == 2" @click="confirmOrder" class="ml20  my-yellow-btn ">同意入住</view>

				<!-- <view @click="confirmOrder" class="ml20  my-yellow-btn ">{{userInfo.role == 2?'同意入住': '联系房东'}}</view> -->
			</view>
			<view v-else-if="orderData.internal_status == 1 && userInfo.role == 1" class="center-all">
				<view v-if="orderData.cancelFlag" @click="cancelOrder" class="my-disable-btn ">取消订单</view>
				<view @click="getPayData" class="ml20  my-yellow-btn "> 立即支付</view>
			</view>
			<view v-else-if="orderData.internal_status == 2 && userInfo.role == 1" class="center-all">
				<view v-if="orderData.cancelFlag" @click="cancelOrder" class="my-disable-btn ">取消订单</view>
				<view  @click="showerweima" class="ml20  my-yellow-btn ">联系ViHome管家</view>
			</view>
			
			<view v-else-if="userInfo.role == 2 &&orderData.internal_status == 9&&!orderData.pre_end_date" class="center-all">
				<view  @click="overOrder" class="my-disable-btn ">结束订单</view>
			</view>
			
			<view v-else-if="(orderData.status == 4 || orderData.status == 6) && orderData.complaint" class="center-all">
				<view  @click="goPayoutDatail" class="my-yellow-btn ">查看损坏追诉</view>
			</view>
			
			
			<view v-else-if="orderData.internal_status == 10 && userInfo.role == 2 " class="center-all">
				<view  @click="goPayoutPage" class="my-yellow-btn ">损坏追诉</view>
				<!-- <view class="ml20  my-yellow-btn "> 联系房东</view> -->
			</view>
		</view>
		<view class="padding36 bg-white mb15">
			<view class="order-item-content">
				<view class="my-m-title oellipsis mb15"> {{orderData.snapshot.info.name}}</view>
				<view class="mb15">
					{{orderData.snapshot.info.rooms[0].name}} <span @click="goHousePage" class="house-tag">房源快照</span>
				</view>
				<view class="justify-start">
					<view class="cover-con">
						<van-image width="239rpx" height="148rpx" fit="cover"
							:src="orderData.snapshot.info.rooms[0].image_urls[0]">
						</van-image>
					</view>
					<view class="step-con">
						<view class="step-item"><span class="dot"></span> 入住{{orderData.start_date}} </view>
						<view class="line"></view>
						<view class="step-item mb10">
							<span class="dot dot2"></span>
						    	退房{{orderData.end_date}}
							<van-icon @click="showCheckoutTime = true" v-if="orderData.end_date_updated_at"  color="#ec8403" name="warning-o" />
						</view>
						<view class="flex-row">
							<view class="tag-color-white mr10">共{{orderData.rent_days}}晚</view>
							<view class="grey-tips f24">均为房源当地时间</view>
						</view>
					</view>
				</view>

				<view v-if="userInfo.role == 1" class="user-info">
					<view class="user-img">
						<van-image width="100%" height="100%" fit="cover" :src="orderData.landlord.avatar_url" />
					</view>
					<view> ViHome管家 {{orderData.snapshot.info.landlord.nickname}}</view>
					<!-- <view class="color-orange num">联系房东 </view> -->
				</view>
				<view v-if="userInfo.role == 1 && orderData.paid_at && orderData.status != 3" class="adress-con">
					<view>{{orderData.addressString}}</view>
					<view @click="openNavigation" class="navigation-btn">导航</view>
				</view>

			</view>
		</view>
		<view class="padding36 bg-white mb15">
			<view v-if="userInfo.role == 2" class="flex-between mb40">
				<view>房客</view>
				<view class="user-info">
					<view class="user-img">
						<van-image width="100%" height="100%" fit="cover" :src="orderData.tenant.avatar_url" />
					</view>
					<view>{{orderData.tenant.nickname}}</view>
					<!-- <view class="color-orange num">联系房客 </view> -->
				</view>
			</view>
			<view class="flex-between mb40">
				<view>入住人数</view>
				<view>{{orderData.adults}}成人{{orderData.kids}}儿童</view>
			</view>
			<view class="flex-between mb40">
				<view>护照</view>
				<view @click="showUpImg">
					已提交
					<van-icon name="arrow" />
				</view>
			</view>
			<view class="flex-between mb40">
				<view>手机号码</view>
				<view>{{orderData.phone || '-'}}</view>
			</view>
			<view class="flex-between mb40">
				<view>订单备注</view>
				<view>{{orderData.remark || '-'}}</view>
			</view>
		</view>
		<view class="padding36 bg-white mb15">
			<view class="flex-between mb40">
				<view>订单编号</view>
				<view>{{orderData.order_number}}</view>
			</view>
			<view class="flex-between mb40">
				<view>下单时间</view>
				<view>{{orderData.created_at}}</view>
			</view>
			<view v-if="orderData.confirmed_at" class="flex-between mb40">
				<view>订单确认</view>
				<view>{{orderData.confirmed_at}}</view>
			</view>
			<view v-if="orderData.paid_at" class="flex-between mb40">
				<view>订单支付</view>
				<view>{{orderData.paid_at}}</view>
			</view>
			<view v-if="orderData.completed_at" class="flex-between mb40">
				<view>订单结束</view>
				<view>{{orderData.completed_at}}</view>
			</view>
			<view v-if="orderData.cancelled_at" class="flex-between mb40">
				<view>订单取消</view>
				<view>{{orderData.cancelled_at}}</view>
			</view>
			<view v-if="orderData.cancel_reason" class="flex-between mb40">
				<view style="min-width: 160rpx ;">取消原因</view>
				<view class="wrap">{{orderData.cancel_reason}}</view>
			</view>


		</view>


		<view class="padding36 bg-white mb15">
			<view class="flex-between mb40">
				<view>押金</view>
				<view>
					{{$formatNumber(orderData.deposit) || '-'}}加元
					（钥匙{{$formatNumber(orderData.deposit_key)}} + 房损{{$formatNumber(orderData.deposit_damage)}}）
				</view>
			</view>
			<view class="grey-tips deposit mb15">由平台监管，退房后10个工作日内自动退回原支付账户</view>
			<view class="flex-between mb40">
				<view>房租</view>
				<view>{{orderData.rent}} 加元</view>
			</view>
			<view class="grey-tips deposit ">{{$formatNumber(orderData.price_public)}}加元/晚x{{orderData.rent_days}}晚
			</view>
			<van-divider :margin="20" />


			<view class="flex-between mb40">
				<view>合计金额</view>
				<view>{{orderData.fee}} 加元</view>
			</view>
			<view class="flex-between mb40">
				<view>优惠</view>
				<view>{{-orderData.discount || 0}} 加元</view>
			</view>

			<view class="flex-between mb40">
				<view class="my-new-m-title">{{Number(orderData.fee_s)?'已付款':'需付款'}}</view>
				<view class="color-red my-new-m-title">
					{{Number(orderData.fee_s) ||$formatNumber( Number(orderData.fee - orderData.discount))}} <span
						class="f28">加元</span>
				</view>
			</view>

			<van-divider v-if="orderData.refund_order" :margin="20" />

			<view  v-if="orderData.refund_order" class="flex-between mb40">
				<view class="my-new-m-title">退款金额
					<span class="color-orange ml10 f28">{{Number(orderData.refund_order.refund_amount_s)?'已退款': '待退款'}}</span></view>
				<view @click="viewRefund" class="color-red my-new-m-title">
					{{Number(orderData.refund_order.refund_amount_s || orderData.refund_order.refund_amount) }} <span
						class="f28 ml10">加元</span>
					<van-icon name="arrow" />
				</view>
			</view>

		</view>

		<van-dialog confirm-button-class="color-orange" id="van-dialog" />

		<erweima :erweimaUrl="orderData.landlord.qr_code_url" ref="erweimaRef">
			<template v-slot:headerTips>
				<view class="grey-tips">微信二维码</view>
			</template>
			<template v-slot:footTips>
				<view class="mb20">长按二维码添加管家微信</view>
			</template>
		</erweima>
		
		<van-dialog
		  use-slot
		  title=" "
		  :show="showCheckoutTime"
		  @confirm="showCheckoutTime = false"
		>
		 <view class=" padding36">
			 <view>原退房日期{{orderData.pre_end_date}}</view>
			 <view class="grey-tips">修改时间{{orderData.end_date_updated_at}} </view>
			 
		 </view>
		</van-dialog>

		
		
	</view>
</template>

<script>
	import Dialog from 'wxcomponents/vant/dialog/dialog';
	import moment from 'moment-timezone';
	import erweima from 'pages/ownr/erweima.vue'
	export default {
		components: {
			erweima
		},
		data() {
			return {
				userInfo: this.$getStorage('userInfo'),
				refundInfo: '',
				orderData: '',
				pageData: '',
				statusList: ['待确认', '待支付', '待入住', '订单已取消', '待退款', '订单已取消', '已结束', '退还押金中', '订单取消待退款', '入住中', '已退房'],
				countDownTime: 0,
				showCheckoutTime: false,
				timer: '',
				payTimer: ''
			
			}
		},
		onLoad(option) {
			this.pageData = option;
		},
		onShow() {
			// 页面显示时监听事件
			clearTimeout(this.timer);
			this.timer = setTimeout(()=>{
				uni.$on('refreshOrderData', this.init);
			},500)
			
		},
		onHide() {
			// 页面隐藏时移除监听
			uni.$off('refreshOrderData', this.init);
		},
		mounted() {
			this.init()

		},

		methods: {
			init() {
				this.getConfiguration();
				this.getOrderData();
			},
			getOrderData() {  // type 2 支付成功获取成功状态
				// this.pageData.orderNumber ='20240830054931407807';
				this.$http.getOrderData(this.pageData.orderNumber).then(res => {
					if (res.status == 1) {
						this.countDownTime = 24 * 1000 * 60 * 60 - (new Date().getTime() - this.$dateToTime(res
							.confirmed_at));
						this.countDownTime = this.countDownTime ? this.countDownTime : 0;
					}

					this.orderData = res;
					this.handData();
				});
			},
			getOrderStatus(num) {
				if(num > 4) {
					uni.hideLoading();
					this.$toast('支付异常，请联系管家确认');
					return;
				}
				this.$http.getOrderData(this.pageData.orderNumber).then(res => {
					if (res.status != 2) {
						clearTimeout(this.payTimer);
						this.payTimer = setTimeout(()=>{
							num++
							this.getOrderStatus(num);
						},3000)
					} else {
						this.$toast('支付成功');
						uni.hideLoading();
						this.orderData = res;
						this.handData();
					}
				});
				
			},
			
			isShowCancel() {
				let nowDate = moment(new Date()).tz(this.orderData.snapshot.info.timezone).format('YYYY/MM/DD HH:mm');
				let startDate = this.orderData.start_date.replace(/-/g, "/");
				let cancelTime = new Date(nowDate).getTime() + 24 * 60 * 60 * 1000;
				this.orderData['cancelFlag'] = true;
				if (cancelTime > new Date(startDate).getTime() && this.orderData.paid_at ) {
					this.orderData['cancelFlag'] = false;
				}
			},
			handData() {
				let dateList = ['created_at', 'confirmed_at', 'paid_at', 'completed_at', 'cancelled_at'];
				dateList.forEach(item => {
					if (this.orderData[item]) {
						this.orderData[item] = this.$timestampToTime(this.orderData[item], 1);
					}
				});
		
				
				let list = ['refund_amount', 'refund_rent', 'refund_rent', 'service_charge', 'refund_amount_s']
				list.forEach(item => {
					if (this.orderData.refund_order && this.orderData.refund_order[item]) {
						this.orderData.refund_order[item] = this.$formatNumber(this.orderData.refund_order[item]);
					}
				})
				this.orderData.rent = this.$formatNumber(this.orderData.rent);
				this.orderData.deposit = this.$formatNumber(this.orderData.deposit);
				this.orderData.fee = this.$formatNumber(this.orderData.fee);
				this.orderData.fee_s = this.$formatNumber(this.orderData.fee_s);

				const {
					info
				} = this.orderData.snapshot;
				let addressString =
					`${info.street_name}, ${info.city.city},${info.city.province},${info.poster_code},${info.city.country}`
				this.orderData['addressString'] = addressString;
				this.$setStorage('orderData', this.orderData);
				this.isShowCancel();
				this.$forceUpdate();
			},
			showUpImg() {
				this.$goPage(1, '/subOrder/uploadPassport?pageType=1'); //1 订单详情  2 其他
			},
			showerweima() {
				this.$refs.erweimaRef.show();
			},

			getConfiguration() {
				this.$http.getConfiguration().then(res => {
					res.forEach(item => {
						if (item.type == 'refund-policy') {
							this.refundInfo = item.content;
						}
					})
				});
			},
			cancelOrder() {
				this.$goPage(1, '/subOrder/cancel')

			},
			viewRefund() {
				this.$goPage(1, '/subOrder/refundDetail')
			},
			overOrder() {
				this.$goPage(1, '/subOrder/overOrder')
			},
			confirmOrder() {
				if (this.userInfo.role == 1) {
					return;
				}
				this.$goPage(1, '/subOrder/confirmOrder')

			},
			goPayoutDatail() {
				this.$goPage(1, '/subOrder/damageDetail')
			},
			getPayData() {
				if (!Number(this.orderData.discount) ) {
					this.payOrder();
					return;
				}
				Dialog.confirm({
						title: '提示',
						confirmButtonText: '确定',
						cancelButtonText: '再想想',
						message: '该订单享有优惠，支付后取消订单，房租不退，是否确定支付？',
					})
					.then(() => {
						this.payOrder();
					})

			},
			payOrder() {
				let data = {
					order_number: this.orderData.order_number
				}
				this.$http.getPayData(data).then(payInfo => {
					
					
					uni.requestPayment({
						timeStamp: payInfo.timeStamp,
						nonceStr: payInfo.nonceStr,
						package: payInfo.package,
						signType: payInfo.signType,
						paySign: payInfo.paySign,
						success: (res) => {
						uni.showLoading({
							title: '订单处理中'
						});
						this.getOrderStatus(1);
						},
						fail: function(res) {

						}
					})
				})
			},
			openNavigation() {
				const {
					info
				} = this.orderData.snapshot;
				const latitude = Number(info.latitude); // 纬度
				const longitude = Number(info.longitude); // 经度
				const name = `${info.city.country}${info.city.province}${info.city.city}`; // 位置名称
				const address = info.street_name; // 详细地址信息

				// 调用API打开导航
				uni.openLocation({
					latitude,
					longitude,
					name,
					address,
					success: function() {
						console.log('导航成功');
					},
					fail: function(err) {
						console.error('导航失败', err);
					}
				});
			},
			jump() {
				this.$goPage(1, '/subNotice/landlady');
			},
			goPayoutPage() {
				this.$goPage(1, '/subOrder/damage')
			},
			goHousePage() {
				let date1 = new Date(this.orderData.start_date.replace(/-/g, "/")).getTime();
				let date2 = new Date(this.orderData.end_date.replace(/-/g, "/")).getTime();
				let selectDate = {
					totalDays: this.orderData.rent_days,
					startDate: this.$timestampToTime1(date1, 2),
					endDate: this.$timestampToTime1(date2, 2),
					startTime: date1,
					endTime: date2,
					beginDate: this.$timestampToTime(date1),
					overDate: this.$timestampToTime(date2)
				}
				this.$setStorage('snapshot', this.orderData.snapshot);
				this.selectDate = this.$setStorage('selectDate', selectDate);
				this.$goPage(1, '/subHouseDetail/homeDetail?pageType=2');
			}
		}
	}
</script>

<style scoped lang="scss">
	.my-page-color {
		padding-bottom: 50rpx;
	}

	.order-item {
		.my-m-title {
			margin: 0 auto;
			// padding: 20rpx 0;

		}
	}

	.order-item-content {
		color: #444;
		background-color: #fff;

		.cover-con {
			width: 239rpx;
			height: 148rpx;
			border-radius: 12rpx;
			overflow: hidden;
			margin-right: 40rpx;
		}

		.step-con {
			// padding: 40rpx 0  0 0;
			// display: flex;
			// align-items: center;
			// flex-direction: column;
		}

		.step-item {
			font-size: 29rpx;
			color: #444444;
			text-indent: 20rpx;
			height: 26rpx;
			line-height: 26rpx;
			display: flex;
			align-items: center;

			.dot {
				width: 15rpx;
				height: 15rpx;
				background: #52C681;
				border-radius: 50%;
				display: inline-block;
				margin-right: 10rpx;
				vertical-align: middle;
			}

			.dot2 {
				background: #E33838;
			}

		}

		.line {
			width: 15rpx;
			height: 30rpx;
			position: relative;
			left: 0;
			top: 0;
		}

		.line::before {
			content: '';
			width: 4rpx;
			height: 40rpx;
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			background-color: #D8D8D8;
		}

	}

	.user-info {
		// width: 100%;
		display: flex;
		align-items: center;
		font-size: 25rpx;
		color: #222222;
		margin-top: 20rpx;

		.user-img {
			width: 60rpx;
			height: 60rpx;
			margin-right: 20rpx;
			border-radius: 50%;
			overflow: hidden;
		}

		.num {
			margin-left: 10rpx;
			font-size: 22rpx;
			// padding-bottom:20rpx ;
		}
	}

	.adress-con {
		width: 678rpx;
		padding: 15rpx 27rpx;
		background: #FFF9F1;
		border-radius: 2rpx;
		border: 2rpx solid #FFE3C0;
		box-sizing: border-box;
		font-weight: 400;
		font-size: 27rpx;
		color: #444;
		margin-top: 15rpx;

		.navigation-btn {
			width: 97rpx;
			height: 36rpx;
			line-height: 36rpx;
			border-radius: 36rpx;
			border: 2rpx solid #EC8403;
			text-align: center;
			font-size: 25rpx;
			color: #EC8403;
			margin-top: 8rpx;
		}
	}

	.deposit {
		font-size: 25rpx;
		text-align: right;
	}

	.introduction {
		font-weight: bold;
		font-size: 43rpx;
		margin: 30rpx 0;

	}

	.small-title {
		font-size: 30rpx;
	}

	.notice {
		display: flex;
		justify-content: space-between;
	}

	.ask-con {
		.ask-item {
			font-size: 30rpx;
			margin-right: 30rpx;
			display: inline-block;
		}
	}

	.money-tips {
		width: 100%;
		padding: 36rpx 36rpx 250rpx 36rpx;
		font-weight: bold;
		font-size: 27rpx;
		box-sizing: border-box;
		// margin-top: 100rpx;
		color: #999;
		display: inline-block;

		.tips-item {
			display: flex;

			span {
				display: inline-block;
				vertical-align: top;
			}
		}
	}

	.house-tag {
		width: 137rpx;
		height: 42rpx;
		border-radius: 2rpx 2rpx 2rpx 2rpx;
		border: 1rpx solid #EC8403;
		line-height: 42rpx;
		margin-left: 15rpx;
		font-size: 25rpx;
		color: #EC8403;
		text-align: center;
		display: inline-block;
	}
</style>
<style>
	.van-count-down {
		color: #EC8403 !important;
		vertical-align: middle;
		line-height: auto !important;
	}
</style>